﻿using FB.Enums;
using FB.Membership;
using FB.Mvc.Controllers;
using FB.Providers;
using FB.Providers.EmployeeInfo;
using FCDB.Entity;
using FCDB.Entity.ConfigEntity;
using FCDB.Repository;
using FCDB.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Wf5.Engine.Business;
using Wf5.Engine.Common;

namespace FCDB.Web.Controllers
{
    [FB.Membership.Annotations.AuthorizeOnly]
    public class ProcessEmployeeController : BaseController
    {
        protected EmployeeInfoUnit _EMPInfoUnit = EmployeeInfoManager.GetEmployeeInfoUnit();
        protected EmployeeInfoService _EMPInfoSvr = EmployeeInfoManager.GetEmployeeInfoService();
        protected IWorkflowService _wfService = new WorkflowService();
        #region 审批人选择对话框
        public ActionResult EmployeeSelect()
        {
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            ViewBag.CustomeFunction = TempData["CustomeFunction"];
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IList<Company> structureList = _EMPInfoUnit.CompanyRepository.Get(t => t.RecordState == RecordState.Active , m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Company item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.COMCode,
                            Value = "Company"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Company",
                            Name = item.Name,
                            spriteCssClass = "treeView_Company"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击公司节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Company")
                {
                    IList<Department> deptList = _EMPInfoUnit.DepartmentRepository.Get(t => t.RecordState == RecordState.Active&& t.COMCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.DEPTCode,
                            Value = "Department"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Department",
                            Name = item.Name,
                            spriteCssClass = "treeView_Department"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击部门节点
                if (keyvalueModel.Value == "Department")
                {
                    IList<Team> teamList = _EMPInfoUnit.TeamRepository.Get(t => t.RecordState == RecordState.Active && t.DEPTCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in teamList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.TEAMCode,
                            Value = "Team"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Team",
                            Name = item.Name,
                            spriteCssClass = "treeView_Team"
                        };
                        EmployeeModelList.Add(model);

                    }
                    IList<EmployeeInPosition> employeePostList = _EMPInfoUnit.EmployeeInPositionRepository.Get(t => t.DEPTCode == keyvalueModel.Key
                        && t.Employee.Status != EmployeeStatus.Terminated).ToList();
                    foreach (var item in employeePostList)
                    {

                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = _EMPInfoUnit.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 展开分组
                if (keyvalueModel.Value == "Team")
                {
                    IList<EmployeeInPosition> employeePostList = _EMPInfoUnit.EmployeeInPositionRepository.Get(t => t.TEAMCode == keyvalueModel.Key
                        && t.Employee.Status != EmployeeStatus.Terminated).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = _EMPInfoUnit.EmployeeRepository.GetByKey(item.EMPCode);

                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            if (TempData["ConditionUserList"] != null)
            {
                IList<ActivityConditionUser> ActivityConditionUserList = (IList<ActivityConditionUser>)TempData["ConditionUserList"];//jsonConverter.Deserialize<List<ActivityConditionUser>>(ConditionUserList);
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (ActivityConditionUser item in ActivityConditionUserList)
                {
                    foreach (var guid in item.UserIDList)
                    {
                        Employee employeeItem = GetEmployeeByUserKey((Guid)guid);
                        item.EmployeeList.Add(new EmployeeModel(employeeItem));
                    }
                    if (item.IsLock)
                    {
                        ViewBag.Lock = item.IsLock;
                    }
                }
                ViewBag.ActivityConditionUserList = ActivityConditionUserList;
            }

            return View();
        }
        public ActionResult RoleSelect(string strUserIDList)
        {

            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IEnumerable<string> structureList = wapper.FindAll();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (string item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item,
                            Value = "Role"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Role",
                            Name = item,
                            spriteCssClass = "treeView_Role"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击角色节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Role")
                {
                    IEnumerable<string> deptList = wapper.FindUserNamesByRole(keyvalueModel.Key);
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        Employee i = GetEmployeeByUserName(item);
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = i.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = i.UserID,
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 展开分组
                if (keyvalueModel.Value == "User")
                {
                    IList<EmployeeInPosition> employeePostList = _EMPInfoUnit.EmployeeInPositionRepository.Get(t => t.Employee.Status != EmployeeStatus.Terminated && t.TEAMCode == keyvalueModel.Key).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = _EMPInfoUnit.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            if (!string.IsNullOrEmpty(strUserIDList))
            {
                IList<Guid> UserIDList = jsonConverter.Deserialize<List<Guid>>(strUserIDList);
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (Guid item in UserIDList)
                {
                    Employee employeeItem = GetEmployeeByUserKey(item);
                    EmployeeList.Add(employeeItem);
                }
                ViewBag.EmployeeList = EmployeeList;
            }
            return View();
        }

        public ActionResult DeparmentSelect(string strUserIDList)
        {

            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IList<Company> structureList = _EMPInfoUnit.CompanyRepository.Get(t => t.RecordState == RecordState.Active , m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Company item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.COMCode,
                            Value = "Company"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Company",
                            Name = item.Name,
                            spriteCssClass = "treeView_Company"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击公司节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Company")
                {
                    IList<Department> deptList = _EMPInfoUnit.DepartmentRepository.Get(t => t.RecordState == RecordState.Active   && t.COMCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.DEPTCode,
                            Value = "Department"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Department",
                            Name = item.Name,
                            spriteCssClass = "treeView_Department"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击部门节点
                if (keyvalueModel.Value == "Department")
                {
                    IList<Team> teamList = _EMPInfoUnit.TeamRepository.Get(t => t.RecordState == RecordState.Active && t.DEPTCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in teamList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.TEAMCode,
                            Value = "Team"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Team",
                            Name = item.Name,
                            spriteCssClass = "treeView_Team"
                        };
                        EmployeeModelList.Add(model);

                    }
                    IList<EmployeeInPosition> employeePostList = _EMPInfoUnit.EmployeeInPositionRepository.Get(t => t.Employee.Status != EmployeeStatus.Terminated && t.DEPTCode == keyvalueModel.Key).ToList();
                    foreach (var item in employeePostList)
                    {

                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = _EMPInfoUnit.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 展开分组
                if (keyvalueModel.Value == "Team")
                {
                    IList<EmployeeInPosition> employeePostList = _EMPInfoUnit.EmployeeInPositionRepository.Get(t => t.Employee.Status != EmployeeStatus.Terminated && t.TEAMCode == keyvalueModel.Key).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = _EMPInfoUnit.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            if (!string.IsNullOrEmpty(strUserIDList))
            {
                IList<Guid> UserIDList = jsonConverter.Deserialize<List<Guid>>(strUserIDList);
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (Guid item in UserIDList)
                {
                    Employee employeeItem = GetEmployeeByUserKey(item);
                    EmployeeList.Add(employeeItem);
                }
                ViewBag.EmployeeList = EmployeeList;
            }
            return View();
        }

        public ActionResult SelectEmployees(string strUserIDList)
        {

            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  搜索
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    string Key = Request["Key"] ?? "";
                    var TrimedKey = Key.Replace(" ", string.Empty);
                    int isLeave = Request["isLeave"].Equals("1")?1:0;
                    List<Employee> EmployeeList;
                    if(isLeave == 1){
                         EmployeeList = _EMPInfoUnit.EmployeeRepository.Get(t =>  t.UserID != null && (t.ChineseName.IndexOf(Key) > -1 || t.UserName.IndexOf(Key) > -1 || t.EMPCode.IndexOf(Key) > -1 || t.RefCode.IndexOf(Key) > -1))
                        .ToList(); 
                    }else{
                        EmployeeList = _EMPInfoUnit.EmployeeRepository.Get(t => t.Status != EmployeeStatus.Terminated && t.UserID != null && (t.ChineseName.IndexOf(Key) > -1 || t.UserName.IndexOf(Key) > -1 || t.EMPCode.IndexOf(Key) > -1 || t.RefCode.IndexOf(Key) > -1))
                        .ToList(); 
                    }

                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Employee item in EmployeeList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = item.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = item.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            return View();
        }

        public ActionResult MyTeamSelect(string strUserIDList)
        {
            MyTeamRepository respository = new MyTeamRepository();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();

            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  获取数据
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    string Key = Request["Key"];
                    IList<MyTeam> MyTeam = respository.GetAllMyTeam(this.UserID);
                    IList<Employee> EmployeeList = new List<Employee>();
                    foreach (var i in MyTeam)
                    {
                        Employee save = new Employee();
                        save = GetEmployeeByUserKey(i.UserID.Value);
                        EmployeeList.Add(save);
                    }
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Employee item in EmployeeList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = item.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = item.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            return View();
        }
        #endregion

        private void GetUserIdsBuyActivity(EmployeeInfoUnit unitinfo, ActivityEntity activity, IList<Guid?> UserIDList, string Company = "", string CosponsorDepartment = "")
        {
            if (activity.NodeType == NodeTypeEnum.EndNode) return;
            IList<String> DeptCodeList = new List<string>();
            #region 部门归属
            if (activity.IsRoleDepartment == true)
            {
                Employee employee = null;
                if (!string.IsNullOrEmpty(Request["AppInstanceID"]) && !string.IsNullOrEmpty(Request["ActivityGuid"]))
                {
                    long AppInstanceID = long.Parse(Request["AppInstanceID"]);
                    WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                    employee = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                }
                else
                {
                    employee = GetEmployeeByUserKey(this.UserID);
                }
                IList<EmployeeInPosition> employeeInPosition = unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employee.EMPCode && t.IsPrimary == true).ToList();
                foreach (var item in employeeInPosition)
                {
                    if (!string.IsNullOrEmpty(item.DEPTCode))
                    {
                        DeptCodeList.Add(item.DEPTCode);
                    }
                }
            }
            #endregion
            #region 协办部门归属
            if (activity.IsCosponsorDepartment == true)
            {
                DeptCodeList.Add(CosponsorDepartment);
            }
            #endregion
            #region 公司归属
            List<String> CompanyList = new List<string>();
            if (activity.IsRoleCompany == true)
            {
                Employee employee = null;
                if (!string.IsNullOrEmpty(Request["AppInstanceID"]) && !string.IsNullOrEmpty(Request["ActivityGuid"]))
                {
                    long AppInstanceID = long.Parse(Request["AppInstanceID"]);
                    WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                    employee = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                }
                else
                {
                    employee = GetEmployeeByUserKey(this.UserID);
                }
                IList<EmployeeInPosition> employeeInPosition = unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employee.EMPCode).ToList();
                foreach (var item in employeeInPosition)
                {
                    if (!string.IsNullOrEmpty(item.COMCode))
                    {
                        CompanyList.Add(item.COMCode);
                    }
                }
            }
            #endregion
            #region 根本角色获取用户并过滤部门归属和公司归属
            foreach (var roleItem in activity.Roles)
            {
                #region 拟稿人
                if (roleItem == "拟稿人")
                {
                    if (string.IsNullOrEmpty(Request["AppInstanceID"]) && !string.IsNullOrEmpty(Request["ActivityGuid"]))
                    {
                        if (!UserIDList.Contains(this.UserID))
                        {
                            UserIDList.Add(this.UserID);
                        }
                    }
                    else
                        if (string.IsNullOrEmpty(Request["AppInstanceID"]) && string.IsNullOrEmpty(Request["ActivityGuid"]))
                        {
                            if (!UserIDList.Contains(this.UserID))
                            {
                                UserIDList.Add(this.UserID);
                            }
                        }
                        else
                        {
                            WfProcessInstance instance = _wfService.GetProcessInstance(int.Parse(Request["AppInstanceID"]));
                            Employee employeeItem = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                            if (!UserIDList.Contains(employeeItem.UserID))
                            {
                                UserIDList.Add(employeeItem.UserID);
                            }
                        }
                    continue;
                }
                #endregion
                AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
                IList<string> userList = wapper.FindAllUsers(roleItem);
                foreach (var useritem in userList)
                {
                    Employee employeeItem = unitinfo.EmployeeRepository.Get(t => t.UserName == useritem && t.UserID.HasValue && t.Status != EmployeeStatus.Terminated).FirstOrDefault();
                    if (null != employeeItem)
                    {
                        IList<PayCompany> CompanysList = ConfigHelper.FinaceCompanyList;
                        if (DeptCodeList.Count == 0 && CompanyList.Count == 0)
                        {
                            if (!UserIDList.Contains(employeeItem.UserID))
                            {
                                
                                    UserIDList.Add(employeeItem.UserID);
                            }
                            continue;
                        }
                        if (DeptCodeList.Count > 0)
                        {
                            if (unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employeeItem.EMPCode && DeptCodeList.Contains(t.DEPTCode)).Count() > 0)
                            {
                                if (!UserIDList.Contains(employeeItem.UserID))
                                {
                                    if (activity.Roles[0].ToString() == "会计" || activity.Roles[0].ToString() == "会计部核实员")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Accountants.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "出纳")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Cashiers.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "财务部负责人" && Company != "")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Leader.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        UserIDList.Add(employeeItem.UserID);
                                    }
                                }
                                continue;
                            }
                        }
                        if (CompanyList.Count > 0)
                        {
                            if (unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employeeItem.EMPCode && CompanyList.Contains(t.COMCode)).Count() > 0)
                            {
                                if (!UserIDList.Contains(employeeItem.UserID))
                                {
                                    if (activity.Roles[0].ToString() == "会计" || activity.Roles[0].ToString() == "会计部核实员")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Accountants.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "出纳")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Cashiers.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "财务部负责人" && Company != "")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Leader.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        UserIDList.Add(employeeItem.UserID);
                                    }
                                }
                                continue;
                            }
                            else
                            {
                                if (!UserIDList.Contains(employeeItem.UserID))
                                {
                                    if (activity.Roles[0].ToString() == "会计" || activity.Roles[0].ToString() == "会计部核实员")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Accountants.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "出纳")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Cashiers.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }
                                    else if (activity.Roles[0].ToString() == "财务部负责人" && Company != "")
                                    {
                                        foreach (var i in CompanysList)
                                        {
                                            if (Company.Contains(i.CompanyName))
                                            {
                                                if (employeeItem.ChineseName == i.Leader.Trim())
                                                    UserIDList.Add(employeeItem.UserID);
                                                break;
                                            }
                                        }
                                    }

                                }
                                continue;
                            }
                        }
                    }
                }
            }
            #endregion
            #region 过滤掉由考勤人员发的单并且考勤部门所在的部门有多个考勤人员
            if (activity.Roles.Count > 0)
            {
                if (activity.Roles[0].ToString() == "考勤记录员")
                {
                    Employee employee = null;
                    if (!string.IsNullOrEmpty(Request["AppInstanceID"]) && !string.IsNullOrEmpty(Request["ActivityGuid"]))
                    {
                        long AppInstanceID = long.Parse(Request["AppInstanceID"]);
                        WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                        employee = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                    }
                    else
                    {
                        employee = GetEmployeeByUserKey(this.UserID);
                    }
                    if (UserIDList.Count > 1)
                    {
                        IList<CustomerServiceEntity> CustomerService = ConfigHelper.CustomerServiceList;
                        foreach (var i in CustomerService)
                        {
                            if (i.CustomerServiceName == employee.ChineseName)
                            {
                                UserIDList.Clear();
                                UserIDList.Add(GetEmployeeByUserName(i.AttendanceLoginName).UserID);
                                break;
                            }
                        }
                    }
                }
            }
            #endregion
        }

        public ActionResult ProcessItemSelect()
        {
            String ProcessGuid = Request["ProcessGuid"];
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            long AppInstanceID = 0;
            long.TryParse(Request["AppInstanceID"], out AppInstanceID);
            String ProcessCheckState = Request["ProcessCheckState"];
            string Lock = "";
            String FormCondition = Request["FormCondition"];
            IDictionary<string, string> conditionKeyPairs = new Dictionary<string, string>();
            if (!String.IsNullOrEmpty(FormCondition))
            {
                List<KeyValueModel> conditions = jsonConverter.Deserialize<List<KeyValueModel>>(FormCondition);
                foreach (var item in conditions)
                {
                    conditionKeyPairs.Add(item.Key, item.Value);
                }
            }
            if (!string.IsNullOrEmpty(ProcessCheckState))
            {
                conditionKeyPairs.Add("CheckState", ProcessCheckState);
            }
            ProcessModel processModel = new ProcessModel(new Guid(ProcessGuid));
            IList<ActivityConditionUser> ConditionUserList = new List<ActivityConditionUser>();
            ActivityEntity activity = null;
            if (AppInstanceID == 0 || Request["ActivityGuid"] == null)
            {
                activity = processModel.GetFirstActivity();
            }
            else
            {
                Guid guid = new Guid(Request["ActivityGuid"]);
                activity = processModel.GetActivity(guid);
            }
            WfAppRunner appRunner = new WfAppRunner()
            {
                AppInstanceID = AppInstanceID,
                UserID = this.UserID,
                UserName = this.UserName,
                ProcessGUID = new Guid(ProcessGuid)
            };
            CurrentRunningNodeMap currentRunning = null;
            currentRunning = _wfService.GetRunningMap(appRunner);
            NextActivityMatchedResult nextActivityMatchedResult = processModel.GetNextActivityList(activity, conditionKeyPairs);
            foreach (var item in nextActivityMatchedResult.Root)
            {
                IList<Guid?> UserIDList = new List<Guid?>();
                string Company = "";
                foreach (var i in conditionKeyPairs)
                {
                    if (i.Key.Trim().IndexOf("CompanyName") > -1)
                        Company = i.Value;
                }
                string CosponsorDepartment = "";
                foreach (var i in conditionKeyPairs)
                {
                    if (i.Key.Trim().IndexOf("CosponsorDeparment") > -1)
                        CosponsorDepartment = i.Value;
                }
                if (currentRunning != null && currentRunning.PreviousActivityInstance != null &&
                    currentRunning.PreviousActivityInstance.ActivityGUID == item.Activity.ActivityGUID && currentRunning.PreviousActivityInstance.EndedByUserID != null)
                {
                    UserIDList.Add(currentRunning.PreviousActivityInstance.EndedByUserID);
                    ActivityConditionUser ActivityConditionUser = new ActivityConditionUser()
                    {
                        ActivityName = item.Activity.ActivityName,
                        UserIDList = UserIDList,
                        ActivityGuid = item.Activity.ActivityGUID,
                        IsAllCheckState = item.Activity.IsAllCheckState,
                        ActivityEntity = item.Activity,
                        IsLock = item.Activity.IsLock
                    };
                    ConditionUserList.Add(ActivityConditionUser);
                }
                else
                {
                    this.GetUserIdsBuyActivity(_EMPInfoUnit, item.Activity, UserIDList, Company, CosponsorDepartment);
                    ActivityConditionUser ActivityConditionUser = new ActivityConditionUser()
                    {
                        ActivityName = item.Activity.ActivityName,
                        UserIDList = UserIDList,
                        ActivityGuid = item.Activity.ActivityGUID,
                        IsAllCheckState = item.Activity.IsAllCheckState,
                        ActivityEntity = item.Activity,
                        IsLock = item.Activity.IsLock
                    };
                    ConditionUserList.Add(ActivityConditionUser);
                }
            }
            if (!CheckIsComplete(ConditionUserList))
            {
                TempData["ConditionUserList"] = ConditionUserList;
                if (!string.IsNullOrEmpty(ProcessCheckState) && int.Parse(ProcessCheckState) != 2)
                {
                    TempData["CustomeFunction"] = activity.CustomeFunction;
                }
                else
                {
                    TempData["CustomeFunction"] = "";
                }
                return RedirectToAction("EmployeeSelect");
            }
            else
            {
                TempData["ConditionUserList"] = ConditionUserList;
                if (!string.IsNullOrEmpty(ProcessCheckState) && int.Parse(ProcessCheckState) != 2)
                {
                    TempData["CustomeFunction"] = activity.CustomeFunction;
                }
                else
                {
                    TempData["CustomeFunction"] = "";
                }
                return RedirectToAction("ProccessComplete");
            }

        }

        public bool CheckIsComplete(IList<ActivityConditionUser> conditionUserList)
        {
            foreach (var item in conditionUserList)
            {
                if (item.ActivityEntity.NodeType == NodeTypeEnum.EndNode)
                {
                    return true;
                }
            }
            return false;
        }
        public ActionResult ProccessComplete(String ConditionUserList)
        {

            if (TempData["ConditionUserList"] != null)
            {
                IList<ActivityConditionUser> ActivityConditionUserList = (IList<ActivityConditionUser>)TempData["ConditionUserList"];
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (ActivityConditionUser item in ActivityConditionUserList)
                {
                    foreach (var guid in item.UserIDList)
                    {
                        Employee employeeItem = GetEmployeeByUserKey((Guid)guid);
                        item.EmployeeList.Add(new EmployeeModel(employeeItem));
                    }
                }
                ViewBag.ActivityConditionUserList = ActivityConditionUserList;
                return View(ActivityConditionUserList);
            }
            return null;

        }
    }
}
